package com.xyht.sca_s.student_manage_system.modules.workApplication.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.data.style.Style;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ApiModelUtil;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.common.util.XWPFTUtil;
import com.xyht.sca_s.student_manage_system.modules.common.constant.FileSavePathConstant;
import com.xyht.sca_s.student_manage_system.modules.newTips.entity.SmsNewTips;
import com.xyht.sca_s.student_manage_system.modules.newTips.entity.SmsNewTipsRecord;
import com.xyht.sca_s.student_manage_system.modules.newTips.mapper.SmsNewTipsMapper;
import com.xyht.sca_s.student_manage_system.modules.newTips.mapper.SmsNewTipsRecordMapper;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.AppTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.RangeTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.TipsTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.util.NewTipsUtil;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.visitor.entity.dto.SmsUserDTO;
import com.xyht.sca_s.student_manage_system.modules.workApplication.entity.SmsWorkApplication;
import com.xyht.sca_s.student_manage_system.modules.workApplication.entity.SmsWorkApplicationDetail;
import com.xyht.sca_s.student_manage_system.modules.workApplication.entity.SmsWorkApplicationProcess;
import com.xyht.sca_s.student_manage_system.modules.workApplication.entity.dto.*;
import com.xyht.sca_s.student_manage_system.modules.workApplication.entity.vo.*;
import com.xyht.sca_s.student_manage_system.modules.workApplication.mapper.SmsWorkApplicationDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.workApplication.mapper.SmsWorkApplicationMapper;
import com.xyht.sca_s.student_manage_system.modules.workApplication.mapper.SmsWorkApplicationMpjMapper;
import com.xyht.sca_s.student_manage_system.modules.workApplication.mapper.SmsWorkApplicationProcessMapper;
import com.xyht.sca_s.student_manage_system.modules.workApplication.service.SmsWorkApplicationService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.agreement.constant.agreementObjectTypeConstant.AGREEMENT_OBJECT_TYPE_PERSON;
import static com.xyht.sca_s.student_manage_system.modules.examinePaymentEquipment.constant.isExportProcessConstant.EXPORT_PROCESS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.examinePaymentEquipment.constant.paymentExamineStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.CopyTypeEnum.COPY_TYPE_ENUM_NONE;
import static com.xyht.sca_s.student_manage_system.modules.student.constant.StudentInfoCommonConstant.PER_SHEET_NUM;
import static com.xyht.sca_s.student_manage_system.modules.workApplication.constant.FileSavePathConstant.FILE_UPLOAD_MAX;
import static com.xyht.sca_s.student_manage_system.modules.workApplication.constant.applicationObjectTypeConstant.WORK_APPLICATION_OBJECT_TYPE_PERSON;
import static com.xyht.sca_s.student_manage_system.modules.workApplication.constant.applicationObjectTypeConstant.WORK_APPLICATION_OBJECT_TYPE_ROLE;
import static com.xyht.sca_s.student_manage_system.modules.workApplication.constant.isAnnexConstant.HAVE_ANNEX;
import static com.xyht.sca_s.student_manage_system.modules.workApplication.constant.workApplicationStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.workApplication.constant.workApplicationTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.workApplicationGroup.constant.workApplicationStatusConstant.WORK_STATUS_FORCED_FINISH;
import static com.xyht.sca_s.student_manage_system.modules.workApplicationGroup.constant.workApplicationStatusConstant.WORK_STATUS_FORCED_REJECT;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-05-17
 */
@Service
public class SmsWorkApplicationServiceImpl extends ServiceImpl<SmsWorkApplicationMapper, SmsWorkApplication> implements SmsWorkApplicationService {
    @Resource
    private FileSavePathConstant fileSavePathConstant;
    @Resource
    private SmsWorkApplicationMapper smsWorkApplicationMapper;

    @Resource
    private SmsWorkApplicationProcessMapper smsWorkApplicationProcessMapper;

    @Resource
    private SmsWorkApplicationDetailMapper smsWorkApplicationDetailMapper;

    @Resource
    private NewTipsUtil newTipsUtil;

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private SmsWorkApplicationMpjMapper smsWorkApplicationMpjMapper;

    @Resource
    private SmsUserMapper smsUserMapper;

    @Resource
    private ApiModelUtil apiModelUtil;

    @Resource
    private SmsRoleMapper smsRoleMapper;
    @Resource
    private SmsNewTipsMapper smsNewTipsMapper;
    @Resource
    private SmsNewTipsRecordMapper smsNewTipsRecordMapper;

    @Transactional
    @Override
    public ResponseResult smsWorkApplicationAdd(SmsWorkApplicationVO smsWorkApplicationVO, String user_id) {
        List<SmsWorkApplicationProcess> fillProcessList =
                smsWorkApplicationProcessMapper.selectList(new QueryWrapper<SmsWorkApplicationProcess>()
                        .lambda()
                        .eq(SmsWorkApplicationProcess::getProcessIsApplicationEdit, true)
                        .eq(SmsWorkApplicationProcess::getProcessIsUse, true)
                        .orderByAsc(SmsWorkApplicationProcess::getProcessSort));
        if (fillProcessList != null && fillProcessList.size() > 0) {
            if (smsWorkApplicationVO.getProcessList() == null || smsWorkApplicationVO.getProcessList().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_USER_NOT_SETTING);
            }
            //判断申请人是否将全部需要编辑流程填写
            List<SmsWorkApplicationProcess> filterList = fillProcessList
                    .stream()
                    .filter(process -> {
                                List<String> result = smsWorkApplicationVO.getProcessList()
                                        .stream()
                                        .filter(fillProcess -> fillProcess.getProcessId().equals(process.getId()))
                                        .map(SmsWorkApplicationDetailVO::getId)
                                        .collect(Collectors.toList());
                                //匹配的去除  未匹配的留下
                                if (result.size() > 0) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }
                    )
                    .collect(Collectors.toList());
            if (filterList.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_PROCESS_NOT_FILL);
            }
        }

        //创建申请表
        SmsWorkApplication addWorkApplication = new SmsWorkApplication();
        BeanUtils.copyProperties(smsWorkApplicationVO, addWorkApplication);
        addWorkApplication.setApplicationApplyUserId(user_id);
        addWorkApplication.setAllowStatus(WORK_STATUS_WAIT_ALLOW);
        addWorkApplication.setUpLoadAnnex(smsWorkApplicationVO.getUpLoadAnnex());
        smsWorkApplicationMapper.insert(addWorkApplication);

        if (addWorkApplication.getId() == null) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        String application_id = addWorkApplication.getId();

        //创建审批流程
        List<SmsWorkApplicationProcess> originProcessList =
                smsWorkApplicationProcessMapper.selectList(new QueryWrapper<SmsWorkApplicationProcess>()
                        .lambda()
                        .eq(SmsWorkApplicationProcess::getProcessIsUse, true)
                        .orderByAsc(SmsWorkApplicationProcess::getProcessSort));
        if (originProcessList == null || originProcessList.size() < 1) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_PROCESS_NOT_SETTING));
        }
        int sort = 1;
        for (SmsWorkApplicationProcess process : originProcessList) {
            //判断管理员是否配置初始流程
            if (!process.getProcessIsApplicationEdit()) {
                if (isNullOrEmpty(process.getProcessObjectId()) || isNullOrEmpty(process.getProcessObjectType())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_PROCESS_NOT_SETTING));
                }
            }

            SmsWorkApplicationDetail addDetail =
                    new SmsWorkApplicationDetail();

            addDetail.setApplicationId(application_id);
            addDetail.setProcessId(process.getId());
            addDetail.setProcessIsSign(process.getProcessIsSign());
            addDetail.setProcessIsStamp(process.getProcessIsStamp());
            addDetail.setProcessName(process.getProcessName());
            addDetail.setDetailAllowStatus(WORK_STATUS_WAIT_ALLOW);

            addDetail.setDetailSort(sort++);



            //申请人可编辑流程
            if (process.getProcessIsApplicationEdit()) {
                List<SmsWorkApplicationDetailVO> filterList = smsWorkApplicationVO.getProcessList()
                        .stream()
                        .filter(fillProcess -> fillProcess.getProcessId().equals(process.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_PROCESS_NOT_FILL));
                }
                SmsWorkApplicationDetailVO fillProcessReq = filterList.get(0);

                if (isNullOrEmpty(fillProcessReq.getProcessObjectId())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
                }
                addDetail.setProcessObjectId(fillProcessReq.getProcessObjectId());
                addDetail.setProcessObjectType(fillProcessReq.getProcessObjectType());
            } else {
                addDetail.setProcessObjectId(process.getProcessObjectId());
                addDetail.setProcessObjectType(process.getProcessObjectType());
            }
            smsWorkApplicationDetailMapper.insert(addDetail);
        }

        //消息通知
        //通知流程第一个节点
        SmsWorkApplicationDetail firstDetail =
                smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                        .lambda()
                        .eq(SmsWorkApplicationDetail::getApplicationId, application_id)
                        .eq(SmsWorkApplicationDetail::getDetailSort, 1)
                        .orderByAsc(SmsWorkApplicationDetail::getDetailSort));
        RangeTypeEnum rangeTypeEnum;
        if(firstDetail.getProcessIsApplicationEdit().equals(1)){
            rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
        }
        else{
            if (firstDetail.getProcessObjectType() == WORK_APPLICATION_OBJECT_TYPE_PERSON) {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            } else {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
            }
        }

        List<String> rangeList = new ArrayList<>();
        rangeList.add(firstDetail.getProcessObjectId());


        newTipsUtil.addNewTips(TipsTypeEnum.TIPS_TYPE_ENUM_ALLOW,
                user_id,
                rangeTypeEnum,
                rangeList,
                COPY_TYPE_ENUM_NONE,
                null,
                AppTypeEnum.APP_TYPE_ENUM_WORK_APPLICATION,
                application_id,
                null,
                null,
                firstDetail.getId(),
                null,
                null,
                null,
                smsWorkApplicationVO.getMessageTitle());
        return CommonResult.success();

    }

    @Override
    public ResponseResult smsWorkApplicationUpdate(SmsWorkApplicationVO smsWorkApplicationVO, String user_id) {
        //查看审批表是否存在且是否为本人
        SmsWorkApplication paymentExamine =
                smsWorkApplicationMapper.selectOne(new QueryWrapper<SmsWorkApplication>()
                        .lambda()
                        .eq(SmsWorkApplication::getId, smsWorkApplicationVO.getApplyId())
                        .eq(SmsWorkApplication::getApplicationApplyUserId, user_id));
        if (paymentExamine == null || isNullOrEmpty(paymentExamine.getId())) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        if (paymentExamine.getAllowStatus() != WORK_STATUS_WAIT_ALLOW) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_CANCEL_FAIL_ALLOWED);
        }
        //修改校验审批节点未审批
        List<SmsWorkApplicationDetail> detailList = smsWorkApplicationDetailMapper.selectList(new LambdaQueryWrapper<SmsWorkApplicationDetail>()
                .eq(SmsWorkApplicationDetail::getApplicationId, smsWorkApplicationVO.getApplyId())
                .eq(SmsWorkApplicationDetail::getDetailSort,1));
        if (detailList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_PROCESS_NOT_EXIST);
        }
        SmsWorkApplicationDetail smsWorkApplicationDetail = detailList.get(0);
        if (smsWorkApplicationDetail.getDetailAllowStatus() != WORK_STATUS_WAIT_ALLOW) {
            return CommonResult.failed(CommonCodeEnum.AGREEMENT_UPDATE_FAIL_ALLOWED);
        }
        //修改申请表
        BeanUtils.copyProperties(smsWorkApplicationVO, paymentExamine);
        smsWorkApplicationMapper.updateById(paymentExamine);

        return CommonResult.success();
    }

    @Transactional
    @Override
    public ResponseResult smsWorkApplicationCancel(SmsWorkApplicationCancelVO smsWorkApplicationCancelVO, String user_id) {
        if (isNullOrEmpty(smsWorkApplicationCancelVO.getApplicationId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //查看审批表是否存在且是否为本人
        SmsWorkApplication paymentExamine =
                smsWorkApplicationMapper.selectOne(new QueryWrapper<SmsWorkApplication>()
                        .lambda()
                        .eq(SmsWorkApplication::getId, smsWorkApplicationCancelVO.getApplicationId())
                        .eq(SmsWorkApplication::getApplicationApplyUserId, user_id));
        if (paymentExamine == null || isNullOrEmpty(paymentExamine.getId())) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        if (paymentExamine.getAllowStatus() != WORK_STATUS_WAIT_ALLOW) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_CANCEL_FAIL_ALLOWED);
        }

//        //判断是否审批中
//        List<SmsWorkApplicationDetail> detailList =
//                smsWorkApplicationDetailMapper.selectList(new QueryWrapper<SmsWorkApplicationDetail>()
//                        .lambda()
//                        .eq(SmsWorkApplicationDetail::getApplicationId, smsWorkApplicationCancelVO.getApplicationId())
//                        .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_PASS));
//        if (detailList != null && detailList.size() > 0) {
//            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_CANCEL_FAIL_ALLOWING);
//        }

        //撤回审批
        SmsWorkApplication cancelExamine = new SmsWorkApplication();
        cancelExamine.setId(smsWorkApplicationCancelVO.getApplicationId());
        cancelExamine.setAllowStatus(WORK_STATUS_CANCEL);
        cancelExamine.setEndTime(new Date());
        smsWorkApplicationMapper.updateById(cancelExamine);

        //修改节点状态
        SmsWorkApplicationDetail cancelExamineDetail = new SmsWorkApplicationDetail();
        cancelExamineDetail.setDetailAllowStatus(WORK_STATUS_CANCEL);

        smsWorkApplicationDetailMapper.update(cancelExamineDetail, new QueryWrapper<SmsWorkApplicationDetail>()
                .lambda()
                .eq(SmsWorkApplicationDetail::getApplicationId, smsWorkApplicationCancelVO.getApplicationId())
                .eq(SmsWorkApplicationDetail::getDetailAllowStatus,WORK_STATUS_WAIT_ALLOW));

        //消息通知
        newTipsUtil.cancelFinishTips(smsWorkApplicationCancelVO.getApplicationId());

        return CommonResult.success();
    }
    @Transactional
    @Override
    public ResponseResult allowSmsWorkApplication(SmsWorkApplicationAllowVO allowVO, String user_id) {
        if (isNullOrEmpty(allowVO.getApplication_id()) || isNullOrEmpty(allowVO.getDetail_id())
                || isNullOrEmpty(allowVO.getDetailAllowStatus())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (allowVO.getDetailAllowStatus() != WORK_STATUS_PASS
                && allowVO.getDetailAllowStatus() != WORK_STATUS_DENY) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsWorkApplicationDetail applicationDetail =
                smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                        .lambda()
                        .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id())
                        .eq(SmsWorkApplicationDetail::getId, allowVO.getDetail_id())
                        .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));
        if (isNullOrEmpty(applicationDetail)) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_FAIL);
        }

        //判断该节点是否本人审批（防止调节点审批）
        if(applicationDetail.getProcessObjectType() == WORK_APPLICATION_OBJECT_TYPE_PERSON){
            if(!applicationDetail.getProcessObjectId().equals(user_id)){
                return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_FAIL);
            }
        }else{
            List<String> roleList = cacheUtil.getRoleList(user_id);
            List<String> filterRoleList = roleList.stream().filter(role -> role.equals(applicationDetail.getProcessObjectId())).collect(Collectors.toList());
            if(filterRoleList.size()<1){
                return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_FAIL);
            }
        }
        if(!applicationDetail.getDetailSort().equals(1)){
            SmsWorkApplicationDetail preDetail =
                    smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                            .lambda()
                            .eq(SmsWorkApplicationDetail::getApplicationId,allowVO.getApplication_id())
                            .eq(SmsWorkApplicationDetail::getDetailSort,applicationDetail.getDetailSort()-1));
            if(preDetail!=null && isNullOrEmpty(preDetail.getId())){
                if(preDetail.getDetailAllowStatus()!=WORK_STATUS_PASS){
                    return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_FAIL);
                }
            }
        }

        SmsWorkApplicationDetail allowDetail = new SmsWorkApplicationDetail();
        allowDetail.setId(allowVO.getDetail_id());
        allowDetail.setDetailAllowStatus(allowVO.getDetailAllowStatus());
        if (!isNullOrEmpty(allowVO.getDetailAllowOpinion())) {
            allowDetail.setDetailAllowOption(allowVO.getDetailAllowOpinion());
        }
        Date nowDate = new Date();
        allowDetail.setDetailAllowTime(nowDate);
        allowDetail.setDetailAllowUserId(user_id);

        if (applicationDetail.getProcessIsSign()) {
            if (isNullOrEmpty(allowVO.getDetailAllowSign())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            allowDetail.setDetailAllowSign(allowVO.getDetailAllowSign());
        }
        if (applicationDetail.getProcessIsStamp()) {
            if (isNullOrEmpty(allowVO.getDetailAllowStamp())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            allowDetail.setDetailAllowStamp(allowVO.getDetailAllowStamp());
        }
        smsWorkApplicationDetailMapper.updateById(allowDetail);

        boolean is_done = false;

        //判断是否最后一个节点 是否驳回
        Integer detailCount = smsWorkApplicationDetailMapper.selectCount(new QueryWrapper<SmsWorkApplicationDetail>()
                .lambda()
                .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id()));
        if (detailCount.equals(applicationDetail.getDetailSort()) || allowVO.getDetailAllowStatus() == WORK_STATUS_DENY) {
            is_done = true;

            SmsWorkApplication updateApplication = new SmsWorkApplication();
            updateApplication.setId(allowVO.getApplication_id());
            updateApplication.setEndTime(nowDate);
            updateApplication.setAllowStatus(allowVO.getDetailAllowStatus());
            smsWorkApplicationMapper.updateById(updateApplication);
        }

        //节点驳回 重置其余节点状态
        if (allowVO.getDetailAllowStatus() == WORK_STATUS_DENY) {
            SmsWorkApplicationDetail updateDenyDetail =
                    new SmsWorkApplicationDetail();
            updateDenyDetail.setDetailAllowStatus(WORK_STATUS_DENY_FINISH);
            smsWorkApplicationDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsWorkApplicationDetail>()
                    .lambda()
                    .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id())
                    .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));
        }


        //消息通知
        if (is_done) {
            boolean result_status = false;
            if (allowVO.getDetailAllowStatus() == WORK_STATUS_PASS) {
                result_status = true;
            }
            newTipsUtil.allowFinishTips(allowVO.getApplication_id(), user_id, result_status);
        } else {
            SmsWorkApplicationDetail nextDetail =
                    smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                            .lambda()
                            .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id())
                            .eq(SmsWorkApplicationDetail::getDetailSort, applicationDetail.getDetailSort() + 1));
            RangeTypeEnum rangeTypeEnum;
            if(nextDetail.getProcessIsApplicationEdit().equals(1)){
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            }
            else{
                if (nextDetail.getProcessObjectType() == WORK_APPLICATION_OBJECT_TYPE_ROLE) {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
                }
                else{
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
                }
            }

            List<String> rangeIDList = new ArrayList<>();
            rangeIDList.add(nextDetail.getProcessObjectId());
            newTipsUtil.allowContinueTips(allowVO.getApplication_id(),
                    user_id,
                    rangeTypeEnum,
                    rangeIDList,
                    nextDetail.getId());
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getSmsWorkApplicationList(String search_str, Integer allowStatus, String user_id, Integer application_type, Integer pageNum, Integer pageSize) {
        if (isNullOrEmpty(application_type)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsWorkApplicationDTO> respList = new ArrayList<>();
        int total = 0;
        if (application_type == WORK_TYPE_APPLY) {
            Page<SmsWorkApplication> page = new Page<>(pageNum, pageSize);
            QueryWrapper<SmsWorkApplication> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SmsWorkApplication::getApplicationApplyUserId, user_id)
                    .orderByDesc(SmsWorkApplication::getCreateTime);
            if(!isNullOrEmpty(search_str)){
                queryWrapper.lambda().and(q ->{
                    q.like(SmsWorkApplication::getAgent,search_str)
                            .or()
                            .like(SmsWorkApplication::getMatter,search_str)
                            .or()
                            .like(SmsWorkApplication::getRequestingUnit,search_str);
                });
            }
            if(!isNullOrEmpty(allowStatus)){
                queryWrapper.lambda().eq(SmsWorkApplication::getAllowStatus,allowStatus);
            }
            smsWorkApplicationMapper.selectPage(page, queryWrapper);
            respList = page.getRecords()
                    .stream()
                    .map(smsWorkApplication -> {
                        SmsWorkApplicationDTO smsWorkApplicationDTO =
                                new SmsWorkApplicationDTO();
                        BeanUtils.copyProperties(smsWorkApplication, smsWorkApplicationDTO);
                        smsWorkApplicationDTO.setApplicationId(smsWorkApplication.getId());

                        SmsUser smsUser = cacheUtil.getUserInfo(smsWorkApplication.getApplicationApplyUserId());
                        SmsWorkApplicationUserDTO smsWorkApplicationUserDTO = new SmsWorkApplicationUserDTO();
                        if (smsUser != null) {
                            BeanUtils.copyProperties(smsUser, smsWorkApplicationUserDTO);
                        }
                        smsWorkApplicationDTO.setApplyUserInfo(smsWorkApplicationUserDTO);

                        return smsWorkApplicationDTO;
                    })
                    .collect(Collectors.toList());
            total = (int) page.getTotal();
        }

        else if (application_type == WORK_TYPE_ALLOWED) {
            Page<SmsWorkApplicationMpjDTO> page = new Page<>(pageNum, pageSize);
            MPJLambdaWrapper<SmsWorkApplicationDetail> mpjLambdaWrapper = new MPJLambdaWrapper<>();
            mpjLambdaWrapper.selectAll(SmsWorkApplicationDetail.class)
                    .selectAll(SmsWorkApplication.class)
                    .selectAs(SmsWorkApplication::getCreateTime, "createTime")
                    .selectAs(SmsWorkApplicationDetail::getId, "detailId")
                    .leftJoin(SmsWorkApplication.class, SmsWorkApplication::getId, SmsWorkApplicationDetail::getApplicationId)
                    .eq(SmsWorkApplicationDetail::getDetailAllowUserId, user_id)
                    //.orderByDesc(SmsWorkApplication::getCreateTime)
                    .orderByDesc(SmsWorkApplicationDetail::getDetailAllowTime)
            ;

            mpjLambdaWrapper.and(wrapper -> {
                wrapper.eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_PASS)
                        .or()
                        .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_DENY);
            });
            if(!isNullOrEmpty(search_str)){
                List<String> userIds = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                        .lambda()
                        .like(SmsUser::getRealName, search_str))
                        .stream()
                        .map(SmsUser::getId).collect(Collectors.toList());

                mpjLambdaWrapper.and(queryWrapper ->{
                    queryWrapper.like(SmsWorkApplication::getAgent,search_str)
                            .or()
                            .like(SmsWorkApplication::getRequestingUnit,search_str)
                            .or()
                            .like(SmsWorkApplication::getMatter,search_str);
                    if(userIds.size() > 0) {
                        queryWrapper.or().in(SmsWorkApplication::getApplicationApplyUserId, userIds);
                    }
                });
            }


            smsWorkApplicationMpjMapper.selectJoinPage(page, SmsWorkApplicationMpjDTO.class, mpjLambdaWrapper);

            respList = page.getRecords()
                    .stream()
                    .map(smsExamineMPJResp -> {
                        SmsWorkApplicationDTO smsWorkApplicationDTO = new SmsWorkApplicationDTO();
                        BeanUtils.copyProperties(smsExamineMPJResp, smsWorkApplicationDTO);
                        smsWorkApplicationDTO.setCreateTime(smsExamineMPJResp.getCreateTime());

                        SmsUser applyUser = cacheUtil.getUserInfo(smsWorkApplicationDTO.getApplicationApplyUserId());
                        SmsWorkApplicationUserDTO smsWorkApplicationUserDTO = new SmsWorkApplicationUserDTO();
                        if (applyUser != null) {
                            BeanUtils.copyProperties(applyUser, smsWorkApplicationUserDTO);
                        }
                        smsWorkApplicationDTO.setApplyUserInfo(smsWorkApplicationUserDTO);

                        SmsUser allowUser = cacheUtil.getUserInfo(smsWorkApplicationDTO.getDetailAllowUserId());
                        SmsWorkApplicationUserDTO smsApplicationAllowUserResp = new SmsWorkApplicationUserDTO();
                        if (allowUser != null) {
                            BeanUtils.copyProperties(allowUser, smsApplicationAllowUserResp);
                        }
                        smsWorkApplicationDTO.setAllowUserInfo(smsApplicationAllowUserResp);

                        return smsWorkApplicationDTO;
                    })
                    .collect(Collectors.toList());
            total = (int) page.getTotal();
        } else if (application_type == WORK_TYPE_ALLOW_WAIT_ME) {
            List<String> roleList = cacheUtil.getRoleList(user_id);

            //获取所有待审批申请流程节点
            List<SmsWorkApplicationDetail> allDetailList =
                    smsWorkApplicationDetailMapper.selectList(new QueryWrapper<SmsWorkApplicationDetail>()
                            .lambda()
                            .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));

            List<SmsWorkApplicationDetail> filterDetailList = allDetailList.stream()
                    .filter(detail -> {
                        if(detail.getProcessIsApplicationEdit().equals(1)){
                            if (!detail.getProcessObjectId().equals(user_id)) {
                                return false;
                            }
                        }
                        else{
                            if (detail.getProcessObjectType() == WORK_APPLICATION_OBJECT_TYPE_PERSON) {
                                if (!detail.getProcessObjectId().equals(user_id)) {
                                    return false;
                                }
                            } else {
                                List<String> filterRoleList = roleList.stream().filter(role -> role.equals(detail.getProcessObjectId())).collect(Collectors.toList());
                                if (filterRoleList.size() < 1) {
                                    return false;
                                }
                            }
                        }


                        if (detail.getDetailSort().equals(1)) {
                            return true;
                        }
                        //判断上一个流程节点是否完成
                        SmsWorkApplicationDetail preDetail =
                                smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                                        .lambda()
                                        .eq(SmsWorkApplicationDetail::getApplicationId, detail.getApplicationId())
                                        .eq(SmsWorkApplicationDetail::getDetailSort, detail.getDetailSort() - 1)
                                        .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_PASS));
                        if (preDetail == null || isNullOrEmpty(preDetail.getId())) {
                            return false;
                        }
                        return true;
                    })
                    .collect(Collectors.toList());
            if (filterDetailList.size() > 0) {
                List<String> detailIDList = filterDetailList.stream().map(SmsWorkApplicationDetail::getId).collect(Collectors.toList());

                Page<SmsWorkApplicationMpjDTO> page = new Page<>(pageNum, pageSize);
                MPJLambdaWrapper<SmsWorkApplicationDetail> mpjLambdaWrapper = new MPJLambdaWrapper<>();
                mpjLambdaWrapper.selectAll(SmsWorkApplicationDetail.class)
                        .selectAll(SmsWorkApplication.class)
                        .selectAs(SmsWorkApplication::getCreateTime, "createTime")
                        .selectAs(SmsWorkApplicationDetail::getId, "detailId")
                        .leftJoin(SmsWorkApplication.class, SmsWorkApplication::getId, SmsWorkApplicationDetail::getApplicationId)
                        .in(SmsWorkApplicationDetail::getId, detailIDList)
                        .orderByDesc(SmsWorkApplication::getCreateTime)
                        .orderByDesc(SmsWorkApplicationDetail::getDetailAllowTime)
                ;
                if(!isNullOrEmpty(search_str)){
                    List<String> userIds = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                            .lambda()
                            .like(SmsUser::getRealName, search_str))
                            .stream()
                            .map(SmsUser::getId).collect(Collectors.toList());

                    mpjLambdaWrapper.and(queryWrapper ->{
                        queryWrapper.like(SmsWorkApplication::getAgent,search_str)
                                .or()
                                .like(SmsWorkApplication::getRequestingUnit,search_str)
                                .or()
                                .like(SmsWorkApplication::getMatter,search_str);
                        if(userIds.size() > 0) {
                            queryWrapper.or().in(SmsWorkApplication::getApplicationApplyUserId, userIds);
                        }
                    });
                }


                smsWorkApplicationMpjMapper.selectJoinPage(page, SmsWorkApplicationMpjDTO.class, mpjLambdaWrapper);

                respList = page.getRecords()
                        .stream()
                        .map(smsExamineMPJResp -> {
                            SmsWorkApplicationDTO smsExamineResp = new SmsWorkApplicationDTO();
                            BeanUtils.copyProperties(smsExamineMPJResp, smsExamineResp);
                            smsExamineResp.setApplicationId(smsExamineMPJResp.getApplicationId());
                            smsExamineResp.setCreateTime(smsExamineMPJResp.getCreateTime());

                            SmsUser applyUser = cacheUtil.getUserInfo(smsExamineResp.getApplicationApplyUserId());
                            SmsWorkApplicationUserDTO smsExamineUserResp = new SmsWorkApplicationUserDTO();
                            if (applyUser != null) {
                                BeanUtils.copyProperties(applyUser, smsExamineUserResp);
                            }
                            smsExamineResp.setApplyUserInfo(smsExamineUserResp);

                            return smsExamineResp;
                        })
                        .collect(Collectors.toList());
                total = (int) page.getTotal();

            }
        }
        return CommonResult.success(respList, total);
    }

    @Override
    public ResponseResult getSmsWorkApplicationDetail(String application_id, String user_id) {
        if (isNullOrEmpty(application_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWorkApplication workApplication = smsWorkApplicationMapper.selectById(application_id);
        if (workApplication == null || isNullOrEmpty(workApplication.getId())) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }

        SmsWorkApplicationDTO workApplicationDTO = new SmsWorkApplicationDTO();
        BeanUtils.copyProperties(workApplication, workApplicationDTO);
        workApplicationDTO.setApplicationId(workApplication.getId());
        workApplicationDTO.setContentAbstract(workApplication.getContentAbstract());
        SmsUser smsUser = cacheUtil.getUserInfo(workApplicationDTO.getApplicationApplyUserId());
        SmsWorkApplicationUserDTO smsWorkApplicationUserDTO = new SmsWorkApplicationUserDTO();
        if (smsUser != null) {
            BeanUtils.copyProperties(smsUser, smsWorkApplicationUserDTO);
        }
        workApplicationDTO.setApplyUserInfo(smsWorkApplicationUserDTO);

        List<SmsWorkApplicationDetailDTO> detailRespList =
                smsWorkApplicationDetailMapper.selectList(new QueryWrapper<SmsWorkApplicationDetail>()
                        .lambda()
                        .eq(SmsWorkApplicationDetail::getApplicationId, application_id)
                        .orderByAsc(SmsWorkApplicationDetail::getDetailSort))
                        .stream()
                        .map(detail -> {
                            SmsWorkApplicationDetailDTO detailResp = new SmsWorkApplicationDetailDTO();
                            BeanUtils.copyProperties(detail, detailResp);
                            if(detailResp.getProcessObjectType()==WORK_APPLICATION_OBJECT_TYPE_PERSON){
                                SmsUser smsUser1 = smsUserMapper.selectById(detailResp.getProcessObjectId());
                                if(!isNullOrEmpty(smsUser1)) {
                                    detailResp.setRealName(smsUser1.getRealName());
                                    detailResp.setHeadPic(smsUser1.getUserPic());
                                }
                            }
                            else if(detailResp.getProcessObjectType()==WORK_APPLICATION_OBJECT_TYPE_ROLE){
                                SmsRole smsRole = smsRoleMapper.selectById(detailResp.getProcessObjectId());
                                if(!isNullOrEmpty(smsRole)) {
                                    detailResp.setRealName(smsRole.getRoleName());
                                }
                            }

                            if (!isNullOrEmpty(detailResp.getDetailAllowUserId())) {
                                SmsUser userInfo = cacheUtil.getUserInfo(detailResp.getDetailAllowUserId());
                                SmsWorkApplicationUserDTO applicationUserDTO = new SmsWorkApplicationUserDTO();
                                if (userInfo != null) {
                                    BeanUtils.copyProperties(userInfo, applicationUserDTO);
                                }
                                detailResp.setAllowUserInfo(applicationUserDTO);
                            }
                            return detailResp;
                        })
                        .collect(Collectors.toList());
        workApplicationDTO.setDetailList(detailRespList);

        return CommonResult.success(workApplicationDTO);
    }

    @Override
    public ResponseResult getSmsWorkApplicationOriginSettingProcess() {
        List<SmsWorkApplicationProcessDTO> respList =
                smsWorkApplicationProcessMapper.selectList(new QueryWrapper<SmsWorkApplicationProcess>()
                        .lambda()
                        .eq(SmsWorkApplicationProcess::getProcessIsApplicationEdit, true)
                        .eq(SmsWorkApplicationProcess::getProcessIsUse,true)
                        .orderByAsc(SmsWorkApplicationProcess::getProcessSort))
                        .stream()
                        .map(process -> {
                            SmsWorkApplicationProcessDTO smsWorkApplicationOriginSettingProcessResp =
                                    new SmsWorkApplicationProcessDTO();
                            BeanUtils.copyProperties(process, smsWorkApplicationOriginSettingProcessResp);
                            return smsWorkApplicationOriginSettingProcessResp;
                        })
                        .collect(Collectors.toList());
        return CommonResult.success(respList);
    }

    //附件上传
    @Override
    public ResponseResult upLoadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String fileName = file.getOriginalFilename();

        int size = Math.round(file.getSize() / 1024);
        int sizeMB = Math.round(size / 1024);
        if (sizeMB > FILE_UPLOAD_MAX) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        }
        log.debug(fileName + "-->" + size + "KB");
        String[] fileTypeArr = fileName.split("\\.");
        String fileType = fileTypeArr[fileTypeArr.length - 1];
        String timeTemp = new Date().getTime() + "";
        String completePath = filePath + timeTemp + "." + fileType;
        String newFileName = timeTemp + "." + fileType;
        File dest = new File(completePath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            Map<String, Object> map = new HashMap<>();
            map.put("oldFileName", fileName);
            map.put("newFileName", newFileName);
            return CommonResult.success(map);
        } catch (MaxUploadSizeExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
    }

    @Override
    public ResponseResult downloadFileManagement(String path, HttpServletResponse response) {
        String fileName = "";
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();
        String completePath = filePath + path;

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                log.debug("fileName=====" + file.getName());
                response.setContentType("application/force-download");

                response.setCharacterEncoding("UTF-8");

                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));

                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
    }

    @Override
    public ResponseResult selectAgent(String person_name) {
        List<SmsUserDTO> list1 = new ArrayList<>();
        if(isNullOrEmpty(person_name)){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        QueryWrapper<SmsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsUser::getRealName,person_name);
        queryWrapper.lambda().eq(SmsUser::getFlag,0);
        SmsUser smsUser = smsUserMapper.selectOne(queryWrapper);
        if(isNullOrEmpty(smsUser)){
            return CommonResult.success(list1,0);
        }
        List<SmsUser> list = smsUserMapper.selectList(queryWrapper);
        if(isNullOrEmpty(list)||list.size()==0){
            return CommonResult.success(list1,0);
        }
        for(SmsUser smsUser1:list){
            SmsUserDTO smsUserDTO = new SmsUserDTO();
            BeanUtils.copyProperties(smsUser1,smsUserDTO);
            list1.add(smsUserDTO);
        }
        return CommonResult.success(list1);
    }

    @Autowired
    XWPFTUtil xwpftUtil;
    @Override
    @Async
    public Future<ResponseResult> tableDownload(String apply_id, HttpServletResponse response) {
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(apply_id);
        if (smsWorkApplication == null || smsWorkApplication.getId() == null) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST));
        }
//        if (smsWorkApplication.getAllowStatus() == WORK_STATUS_WAIT_ALLOW) {
//            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_DOWNLOAD_FAIL));
//        }

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String newFilePath = filePath + apply_id + ".docx";
        String pdfFilePath = filePath + apply_id + ".pdf";

        File pdfFile = new File(pdfFilePath);

   //     if (!pdfFile.exists()) {
            try {

                String isAnnex = "";
                if (smsWorkApplication.getIsAnnex() == HAVE_ANNEX) {
                    isAnnex = "有";
                } else {
                    isAnnex = "无";
                }
                String signTime = TimeUtil.DateHanZiSimpleFormat(smsWorkApplication.getCreateTime());

                List<String> picTagList = new ArrayList<>();
                List<String> textTagList = new ArrayList<>();

                Map<String, Object> map = new HashMap<>();
                map.put("createTime", signTime);
                map.put("requestingUnit", smsWorkApplication.getRequestingUnit());
                map.put("agent", smsWorkApplication.getAgent());
                map.put("isAnnex",isAnnex);
                map.put("matter", smsWorkApplication.getMatter());
                map.put("budgetAmount", smsWorkApplication.getBudgetAmount());
                map.put("contentAbstract", smsWorkApplication.getContentAbstract());
                textTagList.add("contentAbstract");


                //获取初始流程
                List<SmsWorkApplicationProcess> processList = smsWorkApplicationProcessMapper.selectList(new QueryWrapper<SmsWorkApplicationProcess>()
                        .lambda()
                        .orderByAsc(SmsWorkApplicationProcess::getProcessSort));
                if (processList == null || processList.size() < 1) {
                    return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
                }

                //获取申请流程
                List<SmsWorkApplicationDetail> detailList = smsWorkApplicationDetailMapper.selectList(new QueryWrapper<SmsWorkApplicationDetail>()
                        .lambda()
                        .eq(SmsWorkApplicationDetail::getApplicationId, apply_id));
                for (SmsWorkApplicationProcess process : processList) {
                    List<SmsWorkApplicationDetail> filterDetail = detailList
                            .stream()
                            .filter(detail -> detail.getProcessId().equals(process.getId()))
                            .collect(Collectors.toList());
                    if (filterDetail.size() > 0) {
                        SmsWorkApplicationDetail detail = filterDetail.get(0);
                        if (detail.getDetailAllowStatus() == EXAMINE_STATUS_PASS || detail.getDetailAllowStatus() == EXAMINE_STATUS_FORCED_FINISH) {
                            map.put("allowStatus" + process.getProcessSort() + "", "同意");
                        } else if (detail.getDetailAllowStatus() == EXAMINE_STATUS_DENY || detail.getDetailAllowStatus() == EXAMINE_STATUS_FORCED_REJECT) {
                            map.put("allowStatus" + process.getProcessSort() + "", "拒绝");
                        } else {
                            map.put("allowStatus" + process.getProcessSort() + "", "");
                        }

                        map.put("allowOption" + process.getProcessSort() + "", detail.getDetailAllowOption());

                        //添加签名
                        if (isNullOrEmpty(detail.getDetailAllowSign())) {
                            map.put("allowSign" + process.getProcessSort() + "", "");
                        } else {
                            String[] splitStr = detail.getDetailAllowSign().split("=");
                            String fileName = splitStr[splitStr.length - 1];

                            File file = new File(filePath + fileName);
                            if (file.exists()) {
                                InputStream inputStream = new FileInputStream(file);
                                PictureRenderData pictures = Pictures.ofStream(inputStream,
                                        PictureType.PNG).size(60, 60).create();

                                map.put("allowSign" + process.getProcessSort() + "", pictures);
                                picTagList.add("allowSign" + process.getProcessSort());
                            }

                        }

                        //添加印章
                        if (isNullOrEmpty(detail.getDetailAllowStamp())) {
                            map.put("allowStamp" + process.getProcessSort() + "", "");
                        } else {
                            String[] splitStr = detail.getDetailAllowStamp().split("=");
                            String fileName = splitStr[splitStr.length - 1];

                            File file = new File(filePath + fileName);
                            if (file.exists()) {
                                InputStream inputStream = new FileInputStream(file);
                                PictureRenderData pictures = Pictures.ofStream(inputStream,
                                        PictureType.PNG).size(60, 60).create();

                                map.put("allowStamp" + process.getProcessSort() + "", pictures);
                                picTagList.add("allowStamp" + process.getProcessSort());
                            }

                        }

                        //审批时间
                        if (isNullOrEmpty(detail.getDetailAllowTime())) {
                            map.put("detailAllowTime" + process.getProcessSort() + "", "");
                        } else {
                            map.put("detailAllowTime" + process.getProcessSort() + "", TimeUtil.DateHanZiSimpleFormat(detail.getDetailAllowTime()));
                        }
                    } else {
                        map.put("allowStatus" + process.getProcessSort() + "", "");
                        map.put("allowOption" + process.getProcessSort() + "", "");
                        map.put("allowSign" + process.getProcessSort() + "", "");
                        map.put("allowStamp" + process.getProcessSort() + "", "");
                        map.put("detailAllowTime" + process.getProcessSort() + "", "");
                    }
                }


                ClassPathResource resource = new ClassPathResource("applyTemplates/workApplication2.docx");
                InputStream is = resource.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(newFilePath);

                XWPFTemplate template = XWPFTemplate.compile(is);
                //配置图片标签
                Configure config = template.getConfig();
                //图片标签配置
                for (String tag : picTagList
                ) {
                    config.customPolicy(tag, new PictureRenderPolicy());
                }

                //文字标签配置
                for (String textTag: textTagList) {
                    String tagContent = (String) map.get(textTag);
                    if (tagContent != null && tagContent.length() > 30){
                        Style style = new Style();
                        style.setFontSize(8.0);

                        TextRenderData data = new TextRenderData(tagContent,style);
                        map.put(textTag,data);
                    }
                }

                template.render(map);

                template.write(outputStream);

                is.close();
                outputStream.close();
                template.close();

                //word转pdf
                File destOri = new File(newFilePath);
                FileInputStream fileInputStream = new FileInputStream(destOri);
                FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);

                Document document = new Document();
                document.loadFromStream(fileInputStream, FileFormat.Docx);
                //保存为PDF
                document.saveToFile(pdfFilePath, FileFormat.PDF);


                fileInputStream.close();
                fileOutputStream.close();
                document.close();

                log.debug("文件生成完成!");
            } catch (Exception e) {
                e.printStackTrace();
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
            }
  //      }
        try {
            // 加载PDF文档
            PDDocument doc = PDDocument.load(pdfFile);
            doc.setAllSecurityToBeRemoved(true);
            // 创建水印
//            String watermark = "南充电影工业职业学院";
//            PDPageContentStream contentStream;
//
//            for (PDPage page : doc.getPages()) {
//                contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
//
//                //加载字体
//                ClassPathResource resource = new ClassPathResource("fonts/123.ttf");
//                InputStream is = resource.getInputStream();
//                PDFont font = PDType0Font.load(doc, is);
//
//
//                int startX = 0; // 起始位置 x 坐标
//                int startY = 0; // 起始位置 y 坐标
//                float angle = -45; // 角度
//                float interval = 220; // 间隔
//                float opacity = 0.3f; // 透明度
//                int colorR = 127; // 颜色 red 值
//                int colorG = 127; // 颜色 green 值
//                int colorB = 127; // 颜色 blue 值
//
//                //透明的
//                PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
//                r0.setNonStrokingAlphaConstant(opacity);
//                r0.setAlphaSourceFlag(true);
//                contentStream.setGraphicsStateParameters(r0);
//
//                //水印颜色
//                contentStream.setNonStrokingColor(colorR, colorG, colorB);
//                contentStream.beginText();
//                contentStream.setFont(font, 30f);
//
//                int x_times = (int) Math.ceil(page.getMediaBox().getWidth() / interval);
//                int y_times = (int) Math.ceil(page.getMediaBox().getHeight() / interval);
//                for (int x = startX; x <= x_times; x++) {
//                    for (int y = startY; y <= y_times; y++) {
//                        contentStream.setTextRotation(angle, (x * interval), (y * interval));
//                        contentStream.showText(watermark);
//                    }
//                }
//                contentStream.endText();
//                contentStream.restoreGraphicsState();
//                contentStream.close();
//                is.close();
//            }

//            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.pdf;charset=utf-8");
            QueryWrapper<SmsWorkApplication> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SmsWorkApplication::getId,apply_id);
            SmsWorkApplication workApplication = smsWorkApplicationMapper.selectOne(queryWrapper);
            if(isNullOrEmpty(workApplication)){
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND));
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("工作请示单预览("+workApplication.getMatter()+").pdf", "utf-8"));
            response.setHeader("file-name", URLEncoder.encode("工作请示单预览("+workApplication.getMatter()+").pdf", "utf-8"));
            response.setHeader("file-type","download");
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
            //刷新缓冲
            response.flushBuffer();

            // 保存PDF文档
            doc.save(response.getOutputStream());
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));

        }
        return null;

    }

    @Override
    public ResponseResult selectAllApply(String apply_unit, Integer pageSize, Integer pageNum, Integer status) {
        QueryWrapper<SmsWorkApplication> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(apply_unit)) {
            queryWrapper.lambda().like(SmsWorkApplication::getRequestingUnit, apply_unit);
        }
        if(!isNullOrEmpty(status)){
            queryWrapper.lambda().eq(SmsWorkApplication::getAllowStatus,status);
        }
        queryWrapper.orderByDesc("create_time");
        Page<SmsWorkApplication> page = new Page<>(pageNum, pageSize);
        List<SmsWorkApplicationDTO> collect ;

        Page<SmsWorkApplication> appApplicationPage = smsWorkApplicationMapper.selectPage(page, queryWrapper);
        List<SmsWorkApplication> records = appApplicationPage.getRecords();
        collect = records.stream().map(appApplication -> {
            SmsWorkApplicationDTO appApplicationResp = new SmsWorkApplicationDTO();
            BeanUtils.copyProperties(appApplication, appApplicationResp);
            SmsUser smsUser = cacheUtil.getUserInfo(appApplicationResp.getApplicationApplyUserId());
            if (smsUser != null) {
                SmsWorkApplicationUserDTO user = new SmsWorkApplicationUserDTO();
                BeanUtils.copyProperties(smsUser, user);
                appApplicationResp.setApplyUserInfo(user);
            }

            return appApplicationResp;
        }).collect(Collectors.toList());

        int total = (int) page.getTotal();
        return CommonResult.success(collect, total);






        //        List<SmsWorkApplication> list11 = new ArrayList<>();
//        QueryWrapper<SmsWorkApplication> queryWrapper = new QueryWrapper<>();
//        if (isNullOrEmpty(queryWrapper)) {
//            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
//        }
//
//        if (!isNullOrEmpty(apply_unit)) {
//            queryWrapper.lambda().like(SmsWorkApplication::getRequestingUnit, apply_unit);
//        }
//
//        List<SmsWorkApplication> list1 = smsWorkApplicationMapper.selectList(queryWrapper);
//        if (list1.size() == 0) {
//            return CommonResult.success(list11, 0);
//        }
//
//        queryWrapper.orderByDesc("create_time");
//        Page<SmsWorkApplication> page = new Page<>(pageNum, pageSize);
//        smsWorkApplicationMapper.selectPage(page, queryWrapper);
//        list11 = page.getRecords();
//        int total = (int) page.getTotal();
//        return CommonResult.success(list11, total);
    }

    @Override
    @Async
    public Future<ResponseResult> exportWorkApplication(SmsWorkApplicationExportVO exportVO, HttpServletResponse response) {
        if (isNullOrEmpty(exportVO.getIsExportProcess())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        try {
            QueryWrapper<SmsWorkApplication> queryWrapper = new QueryWrapper<>();

            if (!isNullOrEmpty(exportVO.getRequestingUnit())) {
                queryWrapper.lambda().like(SmsWorkApplication::getRequestingUnit, exportVO.getRequestingUnit());
            }

            queryWrapper.lambda().orderByDesc(SmsWorkApplication::getCreateTime);
            List<SmsWorkApplication> list = smsWorkApplicationMapper.selectList(queryWrapper);
            //表头数据
            String[] header = exportVO.getLimitColumn().toArray(new String[0]);
            double sheetNum;
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            if (list != null && list.size() > 0) {
                sheetNum = Math.ceil((double) list.size() / PER_SHEET_NUM);



                for (int k = 0; k < sheetNum; k++) {
                    //生成一个表格，设置表格名称为"资源导出表"
                    HSSFSheet sheet = workbook.createSheet("工作请示单记录导出表" + (k + 1));

                    //设置表格列宽度为10个字节
                    sheet.setDefaultColumnWidth(12);
                    //创建标题的显示样式
                    HSSFCellStyle headerStyle = workbook.createCellStyle();
                    headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
                    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                    HSSFFont f = workbook.createFont();
                    f.setFontHeightInPoints((short) 10);//字号
                    f.setBold(true);//加粗
                    headerStyle.setFont(f);
                    //创建第一行表头
                    HSSFRow headrow = sheet.createRow(0);

                    //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
                    for (int i = 0; i < header.length + 1; i++) {
                        //创建一个单元格
                        HSSFCell cell = headrow.createCell(i);

                        if (i == 0) {
                            //创建一个内容对象
                            HSSFRichTextString text = new HSSFRichTextString("序号");
                            //将内容对象的文字内容写入到单元格中
                            cell.setCellValue(text);
                            cell.setCellStyle(headerStyle);
                            continue;
                        }
                        //创建一个内容对象
                        String header1 = apiModelUtil.getFieldValueByFieldName(SmsWorkApplication.class, header[i - 1]);
                        HSSFRichTextString text = new HSSFRichTextString(header1);

                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                    }

                    //判断是否需要添加流程表头
                    if (exportVO.getIsExportProcess() == EXPORT_PROCESS_TRUE) {
                        List<SmsWorkApplicationProcess> processList =
                                smsWorkApplicationProcessMapper.selectList(new QueryWrapper<>());
                        if (processList != null && processList.size() > 0) {
                            Integer origin_num = header.length + 1;
                            for (SmsWorkApplicationProcess process : processList) {
                                String process_name = process.getProcessName();
                                addProcessTableHead(headrow, headerStyle, origin_num, process_name);
                                origin_num += 4;
                            }
                        }
                    }

                    int range = PER_SHEET_NUM;
                    if (k + 1 == sheetNum) {
                        range = list.size() - (PER_SHEET_NUM) * k;
                    }
                    for (int i = 0; i < range; i++) {
                        //创建一行
                        HSSFRow row1 = sheet.createRow(i + 1);
                        SmsWorkApplication smsWorkApplication = list.get((PER_SHEET_NUM) * k + i);
                        Map map = JSONObject.parseObject(JSON.toJSONString(smsWorkApplication), Map.class);
                        row1.createCell(0).setCellValue(new HSSFRichTextString(i + 1 + ""));
                        for (int j = 0; j < header.length; j++) {
                            String rowContent = "";
                            if (map.get(header[j]) instanceof Long) {
                                rowContent = TimeUtil.DateformatTimestamp((long) map.get(header[j]));
                            } else {
                                if (header[j].equals("applicationApplyUserId")) {
                                    SmsUser smsUser = cacheUtil.getUserInfo(smsWorkApplication.getApplicationApplyUserId());
                                    if (smsUser != null) {
                                        rowContent = smsUser.getRealName();
                                    } else {
                                        rowContent = "";
                                    }
                                } else if (header[j].equals("upLoadAnnex")) {
                                    rowContent = "";
                                } else {
                                    rowContent = (String) map.get(header[j]);
                                }
                            }
                            row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                        }

                        if (exportVO.getIsExportProcess() == EXPORT_PROCESS_TRUE) {
                            List<SmsWorkApplicationProcess> processList =
                                    smsWorkApplicationProcessMapper.selectList(new QueryWrapper<>());
                            if (processList != null && processList.size() > 0) {
                                Integer origin_num = header.length + 1;
                                for (SmsWorkApplicationProcess process : processList) {
                                    SmsWorkApplicationDetail detail =
                                            smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                                                    .lambda()
                                                    .eq(SmsWorkApplicationDetail::getApplicationId, smsWorkApplication.getId())
                                                    .eq(SmsWorkApplicationDetail::getProcessId, process.getId()));
                                    if (detail == null || detail.getId() == null) {
                                        origin_num += 4;
                                    } else {
                                        //审批人
                                        SmsUser user = cacheUtil.getUserInfo(detail.getDetailAllowUserId());
                                        if (user == null) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(user.getRealName()));
                                        }

                                        //审批时间
                                        Date allow_time = detail.getDetailAllowTime();
                                        if (allow_time == null) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(TimeUtil.DateHanZiSimpleFormat(allow_time)));
                                        }

                                        //审批状态
                                        Integer allow_status = detail.getDetailAllowStatus();
                                        if (allow_status == EXAMINE_STATUS_PASS || allow_status == EXAMINE_STATUS_FORCED_FINISH) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString("同意"));
                                        } else if (allow_status == EXAMINE_STATUS_DENY || allow_status == EXAMINE_STATUS_FORCED_REJECT) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString("拒绝"));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        }

                                        //审批意见
                                        String allow_option = detail.getDetailAllowOption();
                                        if (isNullOrEmpty(allow_option)) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(allow_option));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

//            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("工作请示记录导出表.xlsx", "utf-8"));
            response.setCharacterEncoding("utf-8");
            response.setHeader("file-type", "download");
            response.setHeader("file-name", URLEncoder.encode("工作请示记录导出表.xlsx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
//            //刷新缓冲
            response.flushBuffer();
            //workbook将Excel写入到response的输出流中，供页面下载
            OutputStream os = response.getOutputStream();
            workbook.write(os);

            workbook.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return null;
    }



    private void addProcessTableHead(HSSFRow headRow, HSSFCellStyle headerStyle, Integer origin_cell_num, String originHeadContent) {
        Integer cell_num = origin_cell_num;

        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批人");
        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批时间");
        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批状态");
        setTableHead(headRow, headerStyle, cell_num, originHeadContent + "审批意见");

    }
    private void setTableHead(HSSFRow headRow, HSSFCellStyle headerStyle, Integer cell_num, String headContent) {
        HSSFCell cell = headRow.createCell(cell_num);
        //创建一个内容对象
        HSSFRichTextString text = new HSSFRichTextString(headContent);

        //将内容对象的文字内容写入到单元格中
        cell.setCellValue(text);
        cell.setCellStyle(headerStyle);
    }


    @Override
    @Transactional
    public ResponseResult forcedFinishWorkGroupApplication(String applyId, String userId) {
        //校验数据
        if (isNullOrEmpty(applyId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(applyId);
        if(isNullOrEmpty(smsWorkApplication)){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        if(smsWorkApplication.getAllowStatus() != WORK_STATUS_WAIT_ALLOW){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_FORCED);
        }
        //修改审批表状态为通过
        smsWorkApplication.setAllowStatus(WORK_STATUS_PASS);
        smsWorkApplication.setEndTime(new Date());
        smsWorkApplicationMapper.updateById(smsWorkApplication);

        //修改节点为强制归档
        SmsWorkApplicationDetail smsWorkApplicationDetail = new SmsWorkApplicationDetail();
        smsWorkApplicationDetail.setDetailAllowStatus(WORK_STATUS_FORCED_FINISH);
        smsWorkApplicationDetail.setDetailAllowTime(new Date());
        smsWorkApplicationDetail.setDetailAllowUserId(userId);
        smsWorkApplicationDetailMapper.update(smsWorkApplicationDetail,new LambdaQueryWrapper<SmsWorkApplicationDetail>()
                .eq(SmsWorkApplicationDetail::getApplicationId,applyId)
                .eq(SmsWorkApplicationDetail::getDetailAllowStatus,WORK_STATUS_WAIT_ALLOW));

        //消息通知
        newTipsUtil.cancelFinishTips(applyId);

        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult forcedTorsionWorkGroupApplication(SmsWorkApplicationDetailTorsionVO torsionVO) {
        if(isNullOrEmpty(torsionVO.getDetailId(),torsionVO.getApplyId(),torsionVO.getProcessObjectType(),torsionVO.getProcessObjectId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验申请表和节点
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(torsionVO.getApplyId());
        if(isNullOrEmpty(smsWorkApplication)){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        SmsWorkApplicationDetail detail = smsWorkApplicationDetailMapper.selectById(torsionVO.getDetailId());
        if(isNullOrEmpty(detail)){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_DETAIL_NOT_FORCED);
        }
        if(detail.getDetailAllowStatus() != WORK_STATUS_WAIT_ALLOW){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_TORSION);
        }
        detail.setProcessObjectType(torsionVO.getProcessObjectType());
        detail.setProcessObjectId(torsionVO.getProcessObjectId());
        smsWorkApplicationDetailMapper.updateById(detail);
        //消息通知
        //判断第一节点直接发消息,其他要前节点审批后才发该节点通知
        boolean flag = true;
        if(!detail.getDetailSort().equals(1)){
            SmsWorkApplicationDetail beforeDetail = smsWorkApplicationDetailMapper.selectOne(new LambdaQueryWrapper<SmsWorkApplicationDetail>()
                    .eq(SmsWorkApplicationDetail::getApplicationId, torsionVO.getApplyId())
                    .eq(SmsWorkApplicationDetail::getDetailSort, detail.getDetailSort() - 1));
            if(beforeDetail.getDetailAllowStatus() != EXAMINE_STATUS_PASS){
                flag = false;
            }
        }
        if(flag) {
            RangeTypeEnum rangeTypeEnum;
            if (detail.getProcessObjectType() == AGREEMENT_OBJECT_TYPE_PERSON) {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            } else {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
            }
            List<String> rangeList = new ArrayList<>();
            rangeList.add(detail.getProcessObjectId());
            newTipsUtil.allowContinueTips(torsionVO.getApplyId(),
                    null,
                    rangeTypeEnum,
                    rangeList,
                    detail.getId());
        }
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult replaceApplyWorkGroupApplication(String userId, SmsWorkApplicationAllowVO allowVO) {
        if (isNullOrEmpty(allowVO.getApplication_id()) || isNullOrEmpty(allowVO.getDetail_id())
                || isNullOrEmpty(allowVO.getDetailAllowStatus())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (allowVO.getDetailAllowStatus() != WORK_STATUS_PASS
                && allowVO.getDetailAllowStatus() != WORK_STATUS_DENY) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsWorkApplicationDetail applicationDetail =
                smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                        .lambda()
                        .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id())
                        .eq(SmsWorkApplicationDetail::getId, allowVO.getDetail_id())
                        .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));
        if (isNullOrEmpty(applicationDetail)) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_FAIL);
        }


        if(!applicationDetail.getDetailSort().equals(1)){
            SmsWorkApplicationDetail preDetail =
                    smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                            .lambda()
                            .eq(SmsWorkApplicationDetail::getApplicationId,allowVO.getApplication_id())
                            .eq(SmsWorkApplicationDetail::getDetailSort,applicationDetail.getDetailSort()-1));
            if(preDetail!=null && !isNullOrEmpty(preDetail.getId())){
                if(preDetail.getDetailAllowStatus()!=WORK_STATUS_PASS){
                    return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_ALLOW_FAIL);
                }
            }
        }

        SmsWorkApplicationDetail allowDetail = new SmsWorkApplicationDetail();
        allowDetail.setId(allowVO.getDetail_id());
        allowDetail.setDetailAllowStatus(allowVO.getDetailAllowStatus());
        if (!isNullOrEmpty(allowVO.getDetailAllowOpinion())) {
            allowDetail.setDetailAllowOption(allowVO.getDetailAllowOpinion());
        }
        Date nowDate = new Date();
        allowDetail.setDetailAllowTime(nowDate);
        allowDetail.setDetailAllowUserId(userId);
        allowDetail.setDetailAllowSign(allowVO.getDetailAllowSign());
        allowDetail.setDetailAllowStamp(allowVO.getDetailAllowStamp());
        smsWorkApplicationDetailMapper.updateById(allowDetail);

        boolean is_done = false;

        //判断是否最后一个节点 是否驳回
        Integer detailCount = smsWorkApplicationDetailMapper.selectCount(new QueryWrapper<SmsWorkApplicationDetail>()
                .lambda()
                .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id()));
        if (detailCount.equals(applicationDetail.getDetailSort()) || allowVO.getDetailAllowStatus() == WORK_STATUS_DENY) {
            is_done = true;

            SmsWorkApplication updateApplication = new SmsWorkApplication();
            updateApplication.setId(allowVO.getApplication_id());
            updateApplication.setEndTime(nowDate);
            updateApplication.setAllowStatus(allowVO.getDetailAllowStatus());
            smsWorkApplicationMapper.updateById(updateApplication);
        }

        //节点驳回 重置其余节点状态
        if (allowVO.getDetailAllowStatus() == WORK_STATUS_DENY) {
            SmsWorkApplicationDetail updateDenyDetail =
                    new SmsWorkApplicationDetail();
            updateDenyDetail.setDetailAllowStatus(WORK_STATUS_DENY_FINISH);
            smsWorkApplicationDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsWorkApplicationDetail>()
                    .lambda()
                    .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id())
                    .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));
        }


        //消息通知
        if (is_done) {
            boolean result_status = false;
            if (allowVO.getDetailAllowStatus() == WORK_STATUS_PASS) {
                result_status = true;
            }
            newTipsUtil.allowFinishTips(allowVO.getApplication_id(), userId, result_status);
        } else {
            SmsWorkApplicationDetail nextDetail =
                    smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                            .lambda()
                            .eq(SmsWorkApplicationDetail::getApplicationId, allowVO.getApplication_id())
                            .eq(SmsWorkApplicationDetail::getDetailSort, applicationDetail.getDetailSort() + 1));
            RangeTypeEnum rangeTypeEnum;
            if(nextDetail.getProcessIsApplicationEdit().equals(1)){
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            }
            else{
                if (nextDetail.getProcessObjectType() == WORK_APPLICATION_OBJECT_TYPE_ROLE) {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
                }
                else{
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
                }
            }

            List<String> rangeIDList = new ArrayList<>();
            rangeIDList.add(nextDetail.getProcessObjectId());
            newTipsUtil.allowContinueTips(allowVO.getApplication_id(),
                    null,
                    rangeTypeEnum,
                    rangeIDList,
                    nextDetail.getId());
        }
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult forcedRejectWorkGroupApplication(SmsWorkApplicationForceVO forceVO, String userId) {
        if(isNullOrEmpty(forceVO.getApplyId(),forceVO.getDetailAllowOption())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(forceVO.getApplyId());
        if(isNullOrEmpty(smsWorkApplication)){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        //总状态只有待审批才能强制驳回
        Integer allowStatus = smsWorkApplication.getAllowStatus();
        if(allowStatus != WORK_STATUS_WAIT_ALLOW){
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_FORCED_REJECT);
        }
        //修改申请表状态为驳回
        smsWorkApplication.setAllowStatus(WORK_STATUS_DENY);
        smsWorkApplication.setEndTime(new Date());
        smsWorkApplicationMapper.updateById(smsWorkApplication);
        //修改节点状态为强制驳回
        SmsWorkApplicationDetail smsWorkApplicationDetail = new SmsWorkApplicationDetail();
        smsWorkApplicationDetail.setDetailAllowUserId(userId);
        smsWorkApplicationDetail.setDetailAllowStatus(WORK_STATUS_FORCED_REJECT);
        smsWorkApplicationDetail.setDetailAllowTime(new Date());
        smsWorkApplicationDetail.setDetailAllowOption(forceVO.getDetailAllowOption());
        smsWorkApplicationDetailMapper.update(smsWorkApplicationDetail, new LambdaQueryWrapper<SmsWorkApplicationDetail>()
                .eq(SmsWorkApplicationDetail::getApplicationId, forceVO.getApplyId())
                .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));
        //消息提醒
        newTipsUtil.cancelFinishTips(forceVO.getApplyId());
        return CommonResult.success();
    }

    @Override
    public ResponseResult deletedWorkApplication(String applyId) {
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(applyId);
        if (isNullOrEmpty(smsWorkApplication)) {
            return CommonResult.failed(CommonCodeEnum.APPLICATION_NOT_EXIST);
        }

        //删除消息
        List<SmsNewTips> smsNewTipList = smsNewTipsMapper.selectList(new LambdaQueryWrapper<SmsNewTips>().eq(SmsNewTips::getEventId, applyId));
        if (!smsNewTipList.isEmpty()) {
            List<String> newTipsIdList = smsNewTipList.stream().map(SmsNewTips::getId).collect(Collectors.toList());
            smsNewTipsMapper.deleteBatchIds(newTipsIdList);
            smsNewTipsRecordMapper.delete(new LambdaQueryWrapper<SmsNewTipsRecord>().in(SmsNewTipsRecord::getRecordTipsId, newTipsIdList));
        }
        //删除申请表
        smsWorkApplicationMapper.deleteById(applyId);

        //删除节点
        smsWorkApplicationDetailMapper.delete(new LambdaQueryWrapper<SmsWorkApplicationDetail>().eq(SmsWorkApplicationDetail::getApplicationId, applyId));

        return CommonResult.success();
    }

    @Override
    public ResponseResult updateOpinion(SmsWorkApplicationUpdateOpinionVo updateOpinionVo,String userId) {
        if (isNullOrEmpty(updateOpinionVo.getApplyId()) || isNullOrEmpty(updateOpinionVo.getDetailId())
                || isNullOrEmpty(updateOpinionVo.getDetailAllowStatus())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验申请表是否存在
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(updateOpinionVo.getApplyId());
        if (isNullOrEmpty(smsWorkApplication)) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        //校验该节点是否存在,申请人是否是自己
        SmsWorkApplicationDetail applicationDetail =
                smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                        .lambda()
                        .eq(SmsWorkApplicationDetail::getApplicationId, updateOpinionVo.getApplyId())
                        .eq(SmsWorkApplicationDetail::getId, updateOpinionVo.getDetailId())
                        .eq(SmsWorkApplicationDetail::getDetailAllowUserId, userId));
        if (isNullOrEmpty(applicationDetail)) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_PROCESS_NOT_EXIST);
        }

        if (updateOpinionVo.getDetailAllowStatus() != WORK_STATUS_PASS
                && updateOpinionVo.getDetailAllowStatus() != WORK_STATUS_DENY) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }


        //校验不是最后个节点时,下一个节点未审批才能修改意见
        Integer detailSort = applicationDetail.getDetailSort();
        Integer count = smsWorkApplicationDetailMapper.selectCount(new LambdaQueryWrapper<>());
        if (!detailSort.equals(count)){
            SmsWorkApplicationDetail nextDetail = smsWorkApplicationDetailMapper.selectOne(new QueryWrapper<SmsWorkApplicationDetail>()
                    .lambda()
                    .eq(SmsWorkApplicationDetail::getApplicationId, updateOpinionVo.getApplyId())
                    .eq(SmsWorkApplicationDetail::getDetailSort, detailSort + 1));
            if (isNullOrEmpty(nextDetail)) {
                return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_DETAIL_FINAL_ALLOW_FAIL);
            }
            Integer detailAllowStatus = nextDetail.getDetailAllowStatus();
            if (isNullOrEmpty(detailAllowStatus)){
                return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_UPDATE_OPINION_FAIL);
            }
        }
        applicationDetail.setDetailAllowStatus(updateOpinionVo.getDetailAllowStatus());
        if (!isNullOrEmpty(updateOpinionVo.getDetailAllowOpinion())) {
            applicationDetail.setDetailAllowOption(updateOpinionVo.getDetailAllowOpinion());
        }
        Date nowDate = new Date();
        applicationDetail.setDetailAllowTime(nowDate);

        if (applicationDetail.getProcessIsSign()) {
            if (isNullOrEmpty(updateOpinionVo.getDetailAllowSign())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            applicationDetail.setDetailAllowSign(updateOpinionVo.getDetailAllowSign());
        }
        if (applicationDetail.getProcessIsStamp()) {
            if (isNullOrEmpty(updateOpinionVo.getDetailAllowStamp())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            applicationDetail.setDetailAllowStamp(updateOpinionVo.getDetailAllowStamp());
        }
        smsWorkApplicationDetailMapper.updateById(applicationDetail);
        //申请表修改状态
        String applicationId = smsWorkApplication.getId();

        boolean is_done = false;
        if (count.equals(applicationDetail.getDetailSort()) || updateOpinionVo.getDetailAllowStatus() == WORK_STATUS_DENY) {
            is_done = true;

            SmsWorkApplication updateApplication = new SmsWorkApplication();
            updateApplication.setId(updateOpinionVo.getApplyId());
            updateApplication.setEndTime(nowDate);
            updateApplication.setAllowStatus(updateOpinionVo.getDetailAllowStatus());
            smsWorkApplicationMapper.updateById(updateApplication);
        }

        //节点驳回 重置其余节点状态
        SmsWorkApplicationDetail updateDenyDetail =
                new SmsWorkApplicationDetail();
        if (updateOpinionVo.getDetailAllowStatus() == WORK_STATUS_DENY) {

            updateDenyDetail.setDetailAllowStatus(WORK_STATUS_DENY_FINISH);
            smsWorkApplicationDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsWorkApplicationDetail>()
                    .lambda()
                    .eq(SmsWorkApplicationDetail::getApplicationId, updateOpinionVo.getApplyId())
                    .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_WAIT_ALLOW));
        } else{
            updateDenyDetail.setDetailAllowStatus(WORK_STATUS_WAIT_ALLOW);
            smsWorkApplicationDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsWorkApplicationDetail>()
                    .lambda()
                    .eq(SmsWorkApplicationDetail::getApplicationId, updateOpinionVo.getApplyId())
                    .eq(SmsWorkApplicationDetail::getDetailAllowStatus, WORK_STATUS_DENY_FINISH));
        }


            //消息通知
            if (is_done) {
                boolean result_status = false;
                if (updateOpinionVo.getDetailAllowStatus() == WORK_STATUS_PASS) {
                    result_status = true;
                }
                newTipsUtil.allowFinishTips(updateOpinionVo.getApplyId(), userId, result_status);
            } else {
                //之前该节点驳回了,消息重新发起
                if (smsWorkApplication.getAllowStatus() == WORK_STATUS_DENY && updateOpinionVo.getDetailAllowStatus() == WORK_STATUS_PASS) {
                    //查找消息标题
                    String tipsContent = null;
                    List<SmsNewTips> newTipsList = smsNewTipsMapper.selectList(new LambdaQueryWrapper<SmsNewTips>()
                            .eq(SmsNewTips::getEventId, updateOpinionVo.getApplyId())
                            .eq(SmsNewTips::getTipsType, TipsTypeEnum.TIPS_TYPE_ENUM_ALLOW.getValue())
                            .orderByAsc(SmsNewTips::getCreateTime));
                    if (!newTipsList.isEmpty()) {
                        tipsContent = newTipsList.get(0).getTipsContent();
                    }
                    smsWorkApplication.setAllowStatus(WORK_STATUS_WAIT_ALLOW);
                    smsWorkApplicationMapper.updateById(smsWorkApplication);

                    RangeTypeEnum rangeTypeEnum;
                    if (applicationDetail.getProcessObjectType() == WORK_APPLICATION_OBJECT_TYPE_PERSON) {
                        rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
                    } else {
                        rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
                    }
                    List<String> rangeList = new ArrayList<>();
                    rangeList.add(applicationDetail.getProcessObjectId());
                    newTipsUtil.addNewTips(TipsTypeEnum.TIPS_TYPE_ENUM_ALLOW,
                            userId,
                            rangeTypeEnum,
                            rangeList,
                            COPY_TYPE_ENUM_NONE,
                            null,
                            AppTypeEnum.APP_TYPE_ENUM_WORK_APPLICATION,
                            applicationId,
                            null,
                            null,
                            applicationDetail.getId(),
                            null,
                            null,
                            null,
                            tipsContent);

                }
            }
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateAnnex(SmsWorkApplicationUpdateAnnexVo updateAnnexVo, String userId) {
        if (isNullOrEmpty(updateAnnexVo.getApplyId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验申请表是否存在
        SmsWorkApplication smsWorkApplication = smsWorkApplicationMapper.selectById(updateAnnexVo.getApplyId());
        if (isNullOrEmpty(smsWorkApplication)) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_NOT_EXIST);
        }
        //校验是否是自己
        String applicationApplyUserId = smsWorkApplication.getApplicationApplyUserId();
        if (!applicationApplyUserId.equals(userId)) {
            return CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_UPDATE_ANNEX_NOT_USER);
        }
        smsWorkApplication.setIsAnnex(updateAnnexVo.getIsAnnex());
        smsWorkApplication.setUpLoadAnnex(updateAnnexVo.getUpLoadAnnex());
        smsWorkApplicationMapper.updateById(smsWorkApplication);
        return CommonResult.success();
    }

}
